<template>
  <div>
    <p>The current mouse position is ({{ x }}, {{ y }})</p>
    <hr />
    <n-space>
      <n-button :disabled="disabled" @click="buttonClick">{{
        message
      }}</n-button>
      <n-button @click="handleStop">销毁</n-button>
    </n-space>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watchEffect } from "vue";

/**
 * 需求：在页面实时显示鼠标的坐标
 */

const x = ref(0);
const y = ref(0);
function update(event: MouseEvent) {
  x.value = event.pageX;
  y.value = event.pageY;
}

onMounted(() => window.addEventListener("mousemove", update));
onUnmounted(() => window.removeEventListener("mousemove", update));

const count = ref(0);
const message = ref("");
const disabled = ref(false);
let timer: number | null = null;

watchEffect(() => {
  message.value = count.value ? `${count.value}s后重试` : "获取验证码";
  disabled.value = !!count.value;
});

function buttonClick() {
  console.log("获取验证码");
  count.value = 5;
  timer = window.setInterval(() => {
    count.value--;
    if (count.value <= 0 && timer) window.clearInterval(timer);
  }, 1000);
}

function handleStop() {
  timer && window.clearInterval(timer);
  count.value = 0;
}
</script>

<style scoped lang="less"></style>
